// controllers/testController.js
const {
  getWordsFromWordset,
  getRandomWords,
  shuffleArray
} = require("../services/wordService");

const enWords = require("../sequelize/enWords")

const testController = {
  generateTest: (req, res) => {
    try {
      const { userid, wordsetid, num } = req.body;
      const numOptions = 4; // 每个问题的选项总数

      if (!userid || !wordsetid || !num) {
        return res.status(200).send({
          message: "User ID, WordSet ID and number of questions are required",
          success: false,
        });
      }

      getWordsFromWordset(wordsetid, num, (error, correctWordsResult) => {
        if (error) {
          return res
            .status(200)
            .send({ message: error.message, success: false });
        }
        // return {
        //     correctWordsResult
        //   };
        const correctWords = correctWordsResult.map((wordRow) => wordRow.name);
        console.log(correctWords)
        const totalOptionsNeeded = num * (numOptions - 1); // 总共需要的干扰项数量
        getRandomWords(
          totalOptionsNeeded,
          correctWords,
          async (error, optionsResult) => {
            if (error) {
              return res
                .status(200)
                .send({ message: error.message, success: false });
            }

            const allOptions = optionsResult.map((wordRow) => wordRow.name);
            console.log("allOptions:", allOptions)
            let currentOptionIndex = 0; // 用于从 allOptions 选取干扰项
            // 生成答题表
            const questions = []
            for (let i = 0; i < correctWords.length; i++) {
              const correctWord = correctWords[i]
               // 选取干扰项并确保不与正确答案重复
               const options = [(await enWords.findOne({where: {word:correctWord}})).translation];
               while (options.length < numOptions) {
                 const word = await enWords.findOne({where: {word: allOptions[currentOptionIndex++]}})
                 options.push(word.translation);
              }
              questions.push({
                correctWord,
                options: shuffleArray(options),
                correctAnswer: (await enWords.findOne({where: {word:correctWord}})).translation,
              })
            }
            // const questions = correctWords.map(async (correctWord) => {
            //   // 选取干扰项并确保不与正确答案重复
            //   const options = [correctWord];
            //   while (options.length < numOptions) {
            //     const word = await enWords.findOne({where: {word: allOptions[currentOptionIndex++]}})
            //     options.push(word.translation);
            //   }

            //   return {
              // correctWord,
              // options: shuffleArray(options),
              // correctAnswer: (await enWords.findOne({where: {word:correctWord}})).translation,
            //   };
            // });

            const test = {
              userid,
              wordsetid,
              questions,
            };

            // Typically, save the test to the database and return an identifier
            return res.status(200).send({ data: test, success: true });
          }
        );
      });
    } catch (error) {
        console.log(error)
    }
  },

  // ... 其他控制器方法
};

module.exports = testController;
